#include "widget.h"
#include "player1.h"
#include "player2.h"
#include "ui_widget.h"
#include <Qpixmap>
#include<QPushButton>
#include<QGraphicsTextItem>
#include <QObject>
#include<QKeyEvent>

Widget::Widget(QWidget *parent)
    :QWidget(parent)
    , m_Scene1(this)
    ,Player1S(true)
    ,Player2S(false)
    ,BadmintonIsServed(false)
    ,player1Total(0)
    ,player2Total(0)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setFixedSize(1270, 819);
    Startbtn = new QPushButton;
    m_Scene1.setSceneRect(QRect(0, 0, 1270, 819));
    QPixmap bgPixmap1(":/lng/picture/BackGround1.png");
    bgPixmap1 = bgPixmap1.scaled(1270, 819); // 确保图片严格匹配场景尺寸
    m_BackGround1.setPixmap(bgPixmap1);
    m_Scene1.addItem(&m_BackGround1);

    // 关键设置
    m_View.setScene(&m_Scene1);
    m_View.setParent(this);
    m_View.setFixedSize(1271, 823);

    m_View.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_View.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    // 禁用视图变换（可选双重保障）
    m_View.setTransformationAnchor(QGraphicsView::NoAnchor);
    m_View.setResizeAnchor(QGraphicsView::NoAnchor);

    m_View.show();

    //开始按钮
    Startbtn->setParent(this);
    Startbtn->setFixedSize(800,65);
    Startbtn->setStyleSheet(
        "QPushButton {"
        "   border: none;"                        // 去掉边框
        "   background-image: url(:/lng/picture/Startbtn.png);" // 正常状态图片
        "   background-repeat: no-repeat;"        // 禁止重复平铺
        "   background-position: center;"         // 图片居中
        "}"
        "QPushButton:hover {"
        "   background-image: url(:/lng/picture/StartbtnHover.png);"  // 悬停状态图片
        "}"
        );
    Startbtn->move(240,610);
    Startbtn->show();

    connect(Startbtn,&QPushButton::clicked,this,&Widget::InitGame);//点击按钮后切换场景
}
void Widget::InitGame()
{
    //切换游戏场景
    QPixmap bgPixmap1(":/lng/picture/GameBackGround.png");
    bgPixmap1 = bgPixmap1.scaled(1270, 819); // 确保图片严格匹配场景尺寸
    m_Scene2.setSceneRect(QRect(0, 0, 1270, 819));
    m_BackGround2.setPixmap(bgPixmap1);
    m_Scene2.addItem(&m_BackGround2);
    m_View.setScene(&m_Scene2);

    //删除初始按钮
    delete Startbtn;
    Startbtn = nullptr;

    //计数器
    m_counterText = new QGraphicsTextItem;
    m_counterText->setPlainText("Score 0 : 0");
    m_counterText->setDefaultTextColor(Qt::white); // 文字颜色
    m_counterText->setFont(QFont("Arial", 20));     // 字体和大小
    m_counterText->setPos(20, 20);                 // 位置（左上角）
    m_counterText->setZValue(1);                // 确保在最上层
    m_Scene2.addItem(m_counterText);

    //设置Player1
    player1 = new Player1();
    player1->setPos(250,600);
    m_Scene2.addItem(player1);
    m_Scene2.addItem(player1->m_Racket);
    // 假设球拍把手固定在火柴人图片底部中心位置 少了这步一开始球拍不在火柴人身上
    QPointF FixedPos = player1->pos() + QPointF(player1->boundingRect().width() / 2 - 3, player1->boundingRect().height()/2 - 20);
    player1->m_Racket->SetStickPosition(FixedPos);

    player2 = new Player2();
    player2->setPos(1000,600);
    m_Scene2.addItem(player2);
    m_Scene2.addItem(player2->m_Racket);
    // 假设球拍把手固定在火柴人图片底部中心位置 少了这步一开始球拍不在火柴人身上
    QPointF FixedPos1 = player2->pos() + QPointF(player2->boundingRect().width() / 2 - 3, player2->boundingRect().height()/2 - 20);
    player2->m_Racket->SetStickPosition(FixedPos1);

    m_View.setFocus();

    //建立羽毛球
    badminton = new Badminton();
    badminton->setPlayers(player1,player2);


    //绘制空气墙
    // 创建空气墙，这里以场景底部为例
    QGraphicsRectItem *AirWall1 = new QGraphicsRectItem(0 , 0 , 50 , 1000); //左空气墙
    QGraphicsRectItem *AirWall2 = new QGraphicsRectItem(607 , 610 , 40 , 200); //球网空气墙
    QGraphicsRectItem *AirWall3 = new QGraphicsRectItem(1170 , 0 , 50 , 1000); //右空气墙
   // AirWall1->setPen(Qt::NoPen); // 不绘制边框
    m_Scene2.addItem(AirWall1);
   // AirWall2->setPen(Qt::NoPen); // 不绘制边框
    m_Scene2.addItem(AirWall2);
    //AirWall3->setPen(Qt::NoPen); // 不绘制边框
    m_Scene2.addItem(AirWall3);

    badminton->setAirWall(AirWall1,AirWall2,AirWall3);

    // 在InitGame()函数中连接信号
    // 羽毛球创建后添加连接
    connect(badminton, &Badminton::landed, this, &Widget::badmintonLanded);
}
//检测羽毛球落地
//比分增长
void Widget::IncreaseScore(int player1Score, int player2Score) {

    if(BadmintonIsServed)
    {
        player1Total += player1Score;
        player2Total += player2Score;
    }
    
    // 更新显示文本
    m_counterText->setPlainText(QString("Score %1 : %2")
                               .arg(player1Total)
                               .arg(player2Total));
}

// 在badmintonLanded()函数中添加计分逻辑
void Widget::badmintonLanded()
{
    (*badminton).Vx = 0;
    (*badminton).Vy = 0;
    if(m_Scene2.items().contains(badminton))
    {
        if((*badminton).x() > 650)
        {
            // 球落在右侧，玩家1得分
            IncreaseScore(1, 0);  // 玩家1加1分
            Player1S = true;
            Player2S = false;
        }
        if((*badminton).x() < 650)
        {
            // 球落在左侧，玩家2得分
            IncreaseScore(0, 1);  // 玩家2加1分
            Player2S = true;
            Player1S = false;
        }
    }
    player1->Played = !Player1S;
    player2->Played = !Player2S;
    BadmintonIsServed = false;
    badminton->setPos(0,0);
    m_Scene2.removeItem(badminton);
}

void Widget::keyPressEvent(QKeyEvent *event)
{
    switch(event->key())
    {
    case Qt::Key_A:
        (*player1).m_MoveLeftFlag = true;
        (*player1).m_MoveTimer->start(8);
        break;
    case Qt::Key_D:
        (*player1).m_MoveRightFlag = true;
        (*player1).m_MoveTimer->start(8);
        break;
    case Qt::Key_W:
        if(!(*player1).m_MoveUpFlag)
        {
            (*player1).m_MoveUpFlag = true;
            (*player1).m_OriginalY = (*player1).y();
            (*player1).m_JumpTimer->start(8);
        }
        break;
    case Qt::Key_S:
        // 旋转球拍
        if(Player1S&&!BadmintonIsServed)
        {
            m_Scene2.addItem(badminton);
            badminton->setPos((*player1).x(),(*player1).y()-20);
            player1->Played =false;
            player2->Played =true;
            (*badminton).Vx = 12;
            (*badminton).Vy = -14;
            BadmintonIsServed = !BadmintonIsServed;
        }
        if(!(*player1).m_MoveRollFlag)
        {
            (*player1).m_MoveRollFlag = true;
            (*player1).m_RollTimer->start(8);
            (*player1).m_Racket->RotateRacket((*player1).m_RacketAngle);
        }
        break;
    case Qt::Key_J:
        (*player2).m_MoveLeftFlag = true;
        (*player2).m_MoveTimer->start(8);
        break;
    case Qt::Key_L:
       (*player2).m_MoveRightFlag = true;
        (*player2).m_MoveTimer->start(8);
        break;
    case Qt::Key_I:
        if(!(*player2).m_MoveUpFlag)
        {
            (*player2).m_MoveUpFlag = true;
            (*player2).m_OriginalY = (*player2).y();
            (*player2).m_JumpTimer->start(8);
        }
        break;
    case Qt::Key_K:
        if(Player2S&&!BadmintonIsServed)
        {
            m_Scene2.addItem(badminton);
            badminton->setPos((*player2).x(),(*player2).y());
            player2->Played =false;
            player1->Played =true;
            (*badminton).Vx = -12;
            (*badminton).Vy = -14;
            BadmintonIsServed = !BadmintonIsServed;
        }
        // 旋转球拍
        if(!(*player2).m_MoveRollFlag)
        {
            (*player2).m_MoveRollFlag = true;
            (*player2).m_RollTimer->start(8);
            (*player2).m_Racket->RotateRacket((*player2).m_RacketAngle);
        }
        break;
    }
}
void Widget::keyReleaseEvent(QKeyEvent *event)
{
    switch(event->key())
    {
    case Qt::Key_A:
        (*player1).m_MoveLeftFlag = false;
        break;
    case Qt::Key_D:
        (*player1).m_MoveRightFlag = false;
        break;
    case Qt::Key_W://不做操作 在move函数中终止计时器
        break;
    case Qt::Key_S:
        break;
    case Qt::Key_J:
        (*player2).m_MoveLeftFlag = false;
        break;
    case Qt::Key_L:
        (*player2).m_MoveRightFlag = false;
        break;
    case Qt::Key_I://不做操作 在move函数中终止计时器
        break;
    case Qt::Key_K:
        break;
    }

    if (!(*player2).m_MoveLeftFlag && !(*player2).m_MoveRightFlag)
    {
        (*player2).m_MoveTimer->stop();
    }

    if (!(*player1).m_MoveLeftFlag && !(*player1).m_MoveRightFlag)
    {
        (*player1).m_MoveTimer->stop();
    }
}
Widget::~Widget()
{
    delete ui;
}
